/***********************************************************
 *  File_Name  : XJMutex.cpp
 *  File_Path   : 
 *  File_Encode : UTF8
 *  Description : 线程互斥锁类
 *  
 *  OS : Linux, UNIX, Windows
 *  LastVersion  : 20110211
 *      
 *  Author      : LiXiujie(李秀杰)
 *  Date        : 2011-2-11
 *  Version     : 20110211
 *  Description : 
 *                
 *  Edit Author : LiXiujie(李秀杰)
 *  Edit Date   : 2014-8-20
 *  Version     : 20140820
 *  Description : support windows
 *                
 ***********************************************************/

#include "XJMutex.h"
namespace XJUtilClass{
XJMutex::XJMutex() {
	// TODO Auto-generated constructor stub
	int nRet = 0;
#ifndef _WIN32
    pthread_mutexattr_init( & m_attr );
#ifdef __LINUX__
    pthread_mutexattr_settype(& m_attr,PTHREAD_MUTEX_RECURSIVE_NP);
#else
    pthread_mutexattr_settype(& m_attr,PTHREAD_MUTEX_RECURSIVE);
#endif
    nRet = pthread_mutex_init( & m_Mutex, & m_attr);
#else
    InitializeCriticalSection( &m_singlelock);
//    if (!InitializeCriticalSectionAndSpinCount( &m_singlelock, 4096)){
//    	nRet = -1;
//    }
#endif
	if (nRet != 0)
		m_OK = false;
	else
		m_OK = true;
}

XJMutex::~XJMutex() {
	// TODO Auto-generated destructor stub
#ifndef _WIN32
    pthread_mutex_destroy( &m_Mutex );
#else
    DeleteCriticalSection( &m_singlelock );
#endif
}

int XJMutex::Lock(){

	if (m_OK){
		int nRet = 0;
#ifndef _WIN32
		nRet = pthread_mutex_lock( &m_Mutex );
#else
		EnterCriticalSection( &m_singlelock );
#endif
		return nRet;
	}
	else
		return -1;
}
int XJMutex::Unlock(){
	if (m_OK){
		int nRet = 0;
#ifndef _WIN32
		nRet = pthread_mutex_unlock( &m_Mutex );
#else
		LeaveCriticalSection( &m_singlelock );
#endif
		return nRet;
	}
	else
		return -1;
}

int XJMutex::TryLock(){
	if (m_OK){
		int nRet = 0;
#ifndef _WIN32
		nRet = pthread_mutex_trylock(&m_Mutex);
#else
		nRet = -1;
#endif
		return nRet;
	}
	else
		return -1;
}

} //namespace XJUtilClass
